<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { fetchPieChartViewData } from '@/api/view'

const defaultViewdata =
  [
    { name: 'C', value: 12 },
    { name: 'C++', value: 70 },
    { name: 'C#', value: 5 },
    { name: 'Java', value: 45 },
    { name: 'HTML', value: 23 }
  ]

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null,
      viewdata: Object.assign([], defaultViewdata)
    }
  },
  computed: {
    viewdataName() {
      return this.viewdata.map(function (a) {
        var o = a.name;
        return o;
      })
    }
  },
  mounted() {
    this.$nextTick(() => {
      // 获取数据
      this.fetchViewData()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    fetchViewData() {
      fetchPieChartViewData().then(response => {
        this.viewdata = Object.assign(this.viewdata, response.data)
        // 初始化饼状图
        this.initChart()
      }).catch(err => {
        console.log(err)
      })
    },
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          left: 'center',
          bottom: '10',
          data: this.viewdataName
        },
        series: [
          {
            name: '当前标签下帖子数量',
            type: 'pie',
            roseType: 'radius',
            radius: [15, 95],
            center: ['50%', '38%'],
            data: this.viewdata,
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }
        ]
      })
    }
  }
}
</script>
